<?php

namespace app\api\controller;

use app\admin\model\Backprice;
use app\admin\model\detection\Lists;
use app\admin\model\detection\Orders;
use app\admin\model\detection\Prices;
use app\admin\model\Disassemble;
use app\admin\model\disassemble\Info;
use app\admin\model\disassemble\Money;
use app\admin\model\disassemble\Order;
use app\admin\model\Apply;
use app\admin\model\Brand;
use app\admin\model\Article;
use app\admin\model\wddj\CertifiedDrivingAgent;
use app\admin\model\Withdrawal;
use app\api\controller\wddj\user\Map;
use app\api\model\wddj\driver\Driver;
use app\api\model\wddj\user\operation\StartingPrice;
use app\api\model\wddj\user\Payments;
use app\common\controller\Api;
use app\common\model\Category;
use app\common\model\Config;
use addons\aliocr\library\Aliocr;
use app\admin\model\Rescue;
use think\Db;
use fast\Random;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\api\model\wddj\User;
use addons\wddj\library\Wxapp;

/**
 * 边角料接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['getStoreList','channelOrder','autoDriverStatus','configList','articleList','articleDetail','chooseConfig'];
    protected $noNeedRight = ['*'];

    /**
     * @return void
     * @throws \think\exception\DbException
     * 换新补贴列表
     */
    public function articleList()
    {
        $this->success($this->successMsg,Article::order('createtime','desc')->paginate());
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 换新补贴详情
     */
    public function articleDetail()
    {
        $this->success($this->successMsg,Article::where('id',$this->request->param('id'))->find());
    }

    /**
     * @return void
     * 系统配置
     */
    public function configList()
    {
        $this->success($this->successMsg,Config::changeArray($this->request->get('type')));
    }

    /**
     * @return void
     * 选项配置
     */
    public function chooseConfig()
    {
        $this->success($this->successMsg,Category::getCategoryArray($this->request->get('type','cartype'),'normal'));
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 车辆品牌列表
     */
    public function brandList()
    {
        $zimuarr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
//        从数据库中取
//        $brand = new Brand();
//        $list = $brand->order('initial', 'asc')->select();
//        从云端取
        $result = $this->getBrand();
        if(!$result || $result['reason'] != 'success'){
            $this->error($this->errorMsg);
        }
        $list = $result['result'];
        $newdata = [];
        foreach ($list as $value) {
            $newdata[$value['first_letter']][] = $value;
        }
        foreach ($zimuarr as $vv) {
            if (empty($newdata[$vv])) {
                $newdata[$vv] = [];
            }
        }
        ksort($newdata);
        $this->success($this->successMsg, $newdata);
    }
    /**
     * 1452-品牌列表
     */
    public function getBrand()
    {
        // 基本参数配置
        $apiUrl = "http://apis.juhe.cn/cxdq/brand"; // 接口请求URL
        $method = "GET"; // 接口请求方式
        $headers = ["Content-Type: application/x-www-form-urlencoded"]; // 接口请求header
        $apiKey = "259f9d24b7322ac396501ee01f3c743d"; // 在个人中心->我的数据,接口名称上方查看
        // 接口请求入参配置
        $requestParams = [
            'key' => $apiKey,
            'first_letter' => '',
        ];
        $requestParamsStr = http_build_query($requestParams);

        // 发起接口网络请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $apiUrl . '?' . $requestParamsStr);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        if (1 == strpos("$" . $apiUrl, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $response = curl_exec($curl);
        $httpInfo = curl_getinfo($curl);
        curl_close($curl);

        // 解析响应结果
        $responseResult = json_decode($response, true);
        if ($responseResult) {
            // 网络请求成功。可依据业务逻辑和接口文档说明自行处理。
            return $responseResult;
        } else {
            // 网络异常等因素，解析结果异常。可依据业务逻辑自行处理。
            // var_dump($httpInfo);
            return false;
        }
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 加盟平台
     */
    public function commitApply()
    {
        $param = $this->request->post();
        if(empty($param))
            $this->error($this->warningMsg);
        $param['userid'] = $this->auth->id;
        $model = new Apply();
        //判断重复申请
        $check_mobile = $model->where(['mobile'=>$param['mobile']])->find();
        if(!empty($check_mobile))
        {
            $this->error($this->errorMsg = '手机号已被使用');
        }
        $check = $model->where(['userid'=>$param['userid']])->find();
        if(!empty($check))
        {
            $this->errorMsg = $check->status == 0 ? '入驻审核中' : '您已入驻';
            $this->error($this->errorMsg);
        }
        $result = $model->save($param);
        if($result){
            $this->success($this->commitMsg);
        }else{
            $this->error($this->errorMsg);
        }
    }

    /**
     * @return void
     * OCR识别
     */
    public function commonOcr()
    {
        $params = $this->request->param();
        $service = new Aliocr();
        switch ($params['type']) {
            case 'id_card-face':
                $result = $service->ocrIdcard($params['image'], 'face');
                if ($result === false) {
                    $this->error($service->error);
                }
                $data = $service->data;
                $info = array(
                    ['key'=> 'name', 'cn'=> '姓名', 'value'=> $data['name']],
                    ['key'=> 'sex', 'cn'=> '性别', 'value'=> $data['sex']],
                    ['key'=> 'nationality', 'cn'=> '民族', 'value'=> $data['nationality']],
                    ['key'=> 'birth', 'cn'=> '出生', 'value'=> $data['birth']],
                    ['key'=> 'address', 'cn'=> '住址', 'value'=> $data['address']],
                    ['key'=> 'num', 'cn'=> '身份证号', 'value'=> $data['num']]
                );
                break;
            case 'id_card-back':
                $result = $service->ocrIdcard($params['image'], 'back');
                if ($result === false) {
                    $this->error($service->error);
                }
                $data = $service->data;
                $info = array(
                    ['key'=> 'issue', 'cn'=> '签发机关', 'value'=> $data['issue']],
                    ['key'=> 'start_date', 'cn'=> '有效期起始时间', 'value'=> $data['start_date']],
                    ['key'=> 'end_date', 'cn'=> '有效期结束时间', 'value'=> $data['end_date']]
                );
                break;
            case 'vehicle':
                $result = $service->ocrCommon('https://driving.market.alicloudapi.com/rest/160601/ocr/ocr_vehicle.json', $params['image'], ['side'=>'face']);
                if ($result === false) {
                    $this->error($service->error);
                }
                $data = $service->data;
                $info = array(
                    ['key'=> 'plate_num', 'cn'=> '车牌号码', 'value'=> $data['plate_num']],
                    ['key'=> 'vehicle_type', 'cn'=> '车辆类型', 'value'=> $data['vehicle_type']],
                    ['key'=> 'owner', 'cn'=> '所有人名称', 'value'=> $data['owner']],
                    ['key'=> 'model', 'cn'=> '品牌型号', 'value'=> $data['model']],
                    ['key'=> 'vin', 'cn'=> '车辆识别代号', 'value'=> $data['vin']],
                    ['key'=> 'engine_num', 'cn'=> '发动机号码', 'value'=> $data['engine_num']],
                    ['key'=> 'use_character', 'cn'=> '使用性质', 'value'=> $data['use_character']],
                    ['key'=> 'register_date', 'cn'=> '注册日期', 'value'=> $data['register_date']],
                    ['key'=> 'issue_date', 'cn'=> '发证日期', 'value'=> $data['issue_date']],
                );
                break;
            default:
                $this->error($this->warningMsg);
                break;
        }
        $this->success($this->successMsg, $info);
    }

    /**
     * @return void
     * 道路救援提交
     */
    public function commitRescue()
    {
        $params = $this->request->post();
        if(empty($params))
            $this->error($this->warningMsg);
        $model = new Rescue();
        $params['user_id'] = $this->auth->id;
        $result = $model->save($params);
        if(!$result)
            $this->error($this->errorMsg);
        $this->success($this->commitMsg);
    }

    /**
     * @return void
     * 拆解厂/检测厂列表含搜索
     */
    public function getStoreList()
    {
        $params = $this->request->param();
        if(empty($params))
            $this->error($this->warningMsg);
        extract($params);
        $pagesize = 15;
        $begin = ($page-1)*$pagesize;
        $auto_switch = $auto_switch ?? 0;
        $where = 'o.status = 1';
        if(isset($keyword) && $keyword)
            $where .= ' and o.name like "%'.$keyword.'%"';
        if(isset($type) && $type && $table == 'cc_detection')
        {
            if($type == 'check')
                $where .= ' and o.type != 3';
            else
                $where .= ' and o.type != 1';
        }
        if(isset($is_order) && $is_order && $table == 'cc_disassemble')
        {
            if(!isset($weight) || !$weight)
                $this->error('请先输入车重');
            $vehicle_info = Category::get(['name'=>$params['vehicle_type']]);
            if(empty($vehicle_info))
                $this->error('不支持回收该车型');
//            $system_id = Backprice::where(['weight'=>['<=',$weight]])->order('weight','desc')->value('id');

            if(!isset($params['power_type']) || !$params['power_type'])
                $params['power_type'] = '燃油车';
                // $this->error('请先选择动力来源');
            $power_type = in_array($params['power_type'],['增程式','混动车','燃油车']) ? 1 : 2;
            $system_id = Backprice::where(['second_id'=>$vehicle_info->id,'weight'=>['<=',$weight],'end'=>['>=',$weight],'type'=>$power_type])->order('weight','desc')->value('id');
            if(!$system_id)
                $this->error('该车型不支持回收');
            $store_ids = Money::where(['priceid'=>$system_id])->column('store_id');
            if(empty($store_ids))
                $this->error('该车型不支持回收');
            $where .= ' and o.id IN ('.implode(',',$store_ids).')';
        }
        if($auto_switch)
            $where .= ' and o.auto_switch = 1';
        else
            $where .= ' and o.auto_switch = 0';

        $data = Db::query("SELECT truncate(st_distance (POINT($user_lng,$user_lat), POINT(o.longitude,o.latitude))*111195/1000 , 2) as rsdistance,o.* FROM $table AS o  WHERE $where  ORDER BY rsdistance ASC , o.createtime ASC LIMIT $begin,$pagesize");
        foreach ($data as &$item)
        {
            $item['image'] = $this->request->domain().$item['image'];
            $item['tags'] = explode(',',$item['tags']);
            $item['low_price'] = '暂无报价';
            $item['systm_price'] = '暂无补助';
            if(isset($item['json'])){
                $item['json'] = json_decode($item['json'],true);
                if(!empty($item['json'])){
                    array_multisort(array_column($item['json'],'vehicle_price'),SORT_ASC,$item['json']);
                    $item['low_price'] = $item['json'][0]['vehicle_price'];
                    $item['systm_price'] = (Config("site.checkNormalPrice") > Config("site.checkRealPrice")) ? bcmul($item['low_price'],(Config("site.checkNormalPrice") - Config("site.checkRealPrice"))/100,2) : '暂无补助';
                    $vehicle_type = [];
                    foreach ($item['json'] as $json)
                    {
                        $category_name = db('category')->where('id', $json['vehicle_type'])->value('name');
                        if($category_name)
                            $vehicle_type[] = $category_name;
                    }
                    $item['json'] = !empty($vehicle_type) ? $vehicle_type : [];
                }
            }
            if(isset($is_order) && $is_order && $table == 'cc_disassemble'){
                $item['end_price'] = Money::where(['store_id'=>$item['id'],'priceid'=>$system_id])->value('money');
            }
        }
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * 拆解厂/检测厂详情
     */
    public function storeDetail()
    {
        $params = $this->request->param();
        if(empty($params))
            $this->error($this->warningMsg);
        extract($params);
        $data = Db::query("SELECT truncate(st_distance (POINT($user_lng,$user_lat), POINT(o.longitude,o.latitude))*111195/1000 , 2) as rsdistance,o.* FROM $table AS o  WHERE o.status = 1 AND o.id = $storeid  ORDER BY rsdistance ASC , o.createtime ASC limit 0,1");
        if(!empty($data))
        {
            $data = $data[0];
            $data['image'] = $this->request->domain().$data['image'];
            $data['tags'] = explode(',',$data['tags']);
            $data['low_price'] = '暂无报价';
            $data['systm_price'] = '暂无补助';
            if(isset($data['json'])){
                $data['json'] = json_decode($data['json'],true);
                $data['low_price'] = $data['json'][0]['vehicle_price'];
                $data['systm_price'] = (Config("site.checkNormalPrice") > Config("site.checkRealPrice")) ? bcmul($data['low_price'],(Config("site.checkNormalPrice") - Config("site.checkRealPrice"))/100,2) : '暂无补助';
                if(!empty($data['json'])){
                    $vehicle_type = [];
                    foreach ($data['json'] as $json)
                    {
                        $category_name = db('category')->where('id', $json['vehicle_type'])->value('name');
                        if($category_name)
                            $vehicle_type[] = $category_name;
                    }
                    $data['json'] = !empty($vehicle_type) ? $vehicle_type : [];
                }
            }
        }
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * 回收预约
     */
    public function postBackInfo()
    {
        $params = $this->request->post();
        if(empty($params))
            $this->error($this->warningMsg);
        $params['userid'] = $this->auth->id;
        $params['numbers'] = date('YmdHis',time()).Random::numeric(4);
        $vehicle_info = Category::get(['name'=>$params['vehicle_type']]);
        if(empty($vehicle_info))
            $this->error('不支持回收该车型');
        if(!isset($params['power_type']) || !$params['power_type'])
            $params['power_type'] = '燃油车';
            // $this->error('请先选择动力来源');
        $power_type = in_array($params['power_type'],['增程式','混动车','燃油车']) ? 1 : 2;
        $system_id = Backprice::where(['second_id'=>$vehicle_info->id,'weight'=>['<=',$params['car_weight']],'end'=>['>=',$params['car_weight']],'type'=>$power_type])->order('weight','desc')->value('id');
        if(!$system_id)
            $this->error('该车型不支持回收');
        if(!$params['storeids']){
            $params['storeids'] = implode(',',db('store_back_price')->where('priceid',$system_id)->order('money','desc')->value('store_id'));
            if(empty($params['storeids']))
                $this->error('暂无拆解厂报价');
        }
        $storeids = $params['storeids'];
//        $system_id = Backprice::where(['weight'=>['<=',$params['car_weight']]])->order('weight','desc')->value('id');
        $params['end_storeid'] = $storeids;
        $store = [];
        $store = Info::where(['id'=>$storeids])->field('id,name,admin_id,tags,latitude,longitude,file,cfile,address')->find();
        if(empty($store))
            $this->error('拆解厂不存在');
//        $params['end_price'] = Money::where(['priceid'=>$system_id,'store_id'=>$storeids])->value('money');//根据车重获取报价
        // 新增：根据车牌号判断是否在对应地区
        $isInPlateArea = $this->isVehicleInPlateArea($params['plate_num'], $params['city']);

        if($isInPlateArea) {
            // 在车牌号对应地区，使用money字段
            $params['end_price'] = Money::where(['priceid'=>$system_id,'store_id'=>$storeids])->value('money');
        } else {
            // 不在车牌号对应地区，使用ymoney字段
            $params['end_price'] = Money::where(['priceid'=>$system_id,'store_id'=>$storeids])->value('ymoney');
        }
        if(!$params['end_price'])
            $this->error($store['name'].'不支持回收该车型');
        $params['end_adminid'] = $store['admin_id'];
        $params['end_name'] = $store['name'];
        $params['end_tags'] = $store['tags'];
        $params['end_file'] = $store['file'];//委托书
        $params['end_cfile'] = $store['cfile'];//合同
        $params['end_time'] = strtotime("+15 minutes");//确认合作时间
        //判断所有人是企业还是个人
        $params['is_company'] = isCompany($params['owner']) ? 1 : 0;
        $params['createtime'] = time();
        $wechat_id = User::getWechatId($params['userid']);
        Db::startTrans();
        try{
            //代驾费用计算
            $key = (new \app\api\model\wddj\Config())->where('id',1)->value('tencent_map_web_service_key');
            $city_result = getAddress($params['latitude'], $params['longitude'],$key);
            $store_result = getAddress($store->latitude, $store->longitude,$key);
            if(!$city_result || !$store_result)
                throw new Exception('位置信息获取失败');
            //下代驾订单
            $car_order = [
                'type'=> 2,
                'city'=>  $city_result['city'],
                'to_city'=>($store_result['province'].'/'.$store_result['city'].'/'.$store_result['district']),
                'city_type'=>$vehicle_info->pid,//城市代驾规则中的车辆类型
                'to_address'=> $store->address,
                'to_lat'=> $store->latitude,
                'to_lng'=> $store->longitude,
                'from_address'=> $params['city'].$params['address'],
                'from_lat'=> $params['latitude'],
                'from_lng'=> $params['longitude'],
                'driver_number'=> 1,
                'departure_time'=> date('Y-m-d H:i',$params['gettime']),
                'is_check'=>0
            ];
            $order_result = \app\api\model\wddj\user\Order::autoCreate($car_order,$wechat_id);
            if(!is_array($order_result))
                throw new Exception($order_result);
            $params['estimated_amount'] = $order_result['estimated_amount'];
            $params['out_trade_no'] = $order_result['out_trade_no'];
            //拖车费用计算
            $car_order_trailer = [
                'type'=> 2,
                'city'=>  $city_result['city'],
                'to_city'=>($store_result['province'].'/'.$store_result['city'].'/'.$store_result['district']),
                'city_type'=>$vehicle_info->pid,//城市代驾规则中的车辆类型
                'to_address'=> $store->address,
                'to_lat'=> $store->latitude,
                'to_lng'=> $store->longitude,
                'from_address'=> $params['city'].$params['address'],
                'from_lat'=> $params['latitude'],
                'from_lng'=> $params['longitude'],
                'driver_number'=> 1,
                'departure_time'=> date('Y-m-d H:i',$params['gettime']),
            ];
            $order_result_trailer = \app\api\model\wddj\usert\Order::autoCreateNoTrailer($car_order_trailer,$wechat_id);
            if(!is_array($order_result_trailer))
                throw new Exception($order_result_trailer);
            $params['tuoche_amount'] = $order_result_trailer['estimated_amount'];
            $params['tuoche_trade_no'] = $order_result_trailer['out_trade_no'];

            if($params['is_diving'] == 1)
            {
                $params['end_price'] += $params['estimated_amount'];
            }else if($params['is_diving'] == 2)
            {
                $params['end_price'] += $params['tuoche_amount'];
            }
            $res = db('back_order')->insert($params);
            if(!$res)
                throw new Exception('下单失败，稍后再试');
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success($this->successMsg);
    }
    /**
     * 判断车辆是否在车牌号对应地区
     * @param string $plateNum 车牌号
     * @param string $currentCity 当前地区（格式：河南省/郑州市/金水区）
     * @return bool
     */
    private function isVehicleInPlateArea($plateNum, $currentCity)
    {
        // 获取车牌号对应的地区
        $plateArea = $this->getAreaByPlate($plateNum);
        if (!$plateArea) {
            return false; // 无法识别车牌地区，默认不在对应地区
        }

        // 比较当前地区是否包含车牌地区
        return strpos($currentCity, $plateArea) !== false;
    }

    /**
     * 根据车牌号获取对应地区
     * @param string $plateNum 车牌号
     * @return string|false
     */
    private function getAreaByPlate($plateNum)
    {
        // 车牌号地区映射表（需要根据实际情况完善）
        $plateAreaMap = [
            // 省份简称 => 省份全称
            '京' => '北京',
            '津' => '天津',
            '沪' => '上海',
            '渝' => '重庆',
            '冀' => '河北',
            '晋' => '山西',
            '辽' => '辽宁',
            '吉' => '吉林',
            '黑' => '黑龙江',
            '苏' => '江苏',
            '浙' => '浙江',
            '皖' => '安徽',
            '闽' => '福建',
            '赣' => '江西',
            '鲁' => '山东',
            '豫' => '河南',
            '鄂' => '湖北',
            '湘' => '湖南',
            '粤' => '广东',
            '琼' => '海南',
            '川' => '四川',
            '贵' => '贵州',
            '云' => '云南',
            '陕' => '陕西',
            '甘' => '甘肃',
            '青' => '青海',
            '台' => '台湾',
            '蒙' => '内蒙古',
            '桂' => '广西',
            '宁' => '宁夏',
            '新' => '新疆',
            '藏' => '西藏',
            '港' => '香港',
            '澳' => '澳门',
        ];

        if (empty($plateNum) || strlen($plateNum) < 2) {
            return false;
        }

        // 获取车牌第一个字符（省份简称）
        $provinceShort = mb_substr($plateNum, 0, 1, 'UTF-8');

        // 从映射表中获取省份全称
        if (isset($plateAreaMap[$provinceShort])) {
            return $plateAreaMap[$provinceShort];
        }

        return false;
    }
    /**
     * @return void
     * 订单列表
     */
    public function orderList()
    {
        $type = $this->request->get('type',0);//0=报废订单,1=检测订单,2=代驾订单
        $model = $type == 0 ? new Order() : ($type == 1 ? new Orders() : new Order());
        $this->success($this->successMsg,$model->where(['userid'=>$this->auth->id])->order(['id'=>'desc'])->paginate());
    }

    /**
     * @return void
     * 订单详情
     */
    public function orderDetail()
    {
        $type = $this->request->get('type',0);//0=报废订单,1=检测订单,2=代驾订单
        $order_id = $this->request->get('order_id',0);
        $model = $type == 0 ? new Order() : ($type == 1 ? new Orders() : new Order());
        $data = $model->where(['userid'=>$this->auth->id,'id'=>$order_id])->find();
        if($type == 0)
            $data['end_json'] = json_decode($data['end_json']);
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 客户选择拆解厂
     */
    public function chooseStore()
    {
        $params = $this->request->post();
        if(empty($params))
            $this->error($this->warningMsg);
        extract($params);
        $model = new Order();
        $data = $model->find($order_id);
        if(empty($data))
            $this->error($this->warningMsg);
        if($data->status != 0)
            $this->error($this->errorMsg = '已确认');
        if(empty($data->price_json))
            $this->error($this->errorMsg = '请等待厂商报价');
        $choose = [];
        foreach ($data->price_json as $json)
        {
            if($json['id'] == $store_id)
                $choose = $json;
        }
        $data->end_storeid = $choose['id'];
        $data->end_price = $choose['price'];
        $data->end_name = $choose['name'];
        $data->end_tags = $choose['tags'];
        $data->end_adminid = $choose['admin_id'];
        $data->confirmtime = time();
        $store = Info::where(['id'=>$data->end_storeid])->field('longitude,latitude')->find();
        $mapResult = (new Map())->get_driver_routes([
            'from_lat'=>$data->latitude,
            'from_lng'=>$data->longitude,
            'to_lat'=>$store->latitude,
            'to_lng'=>$store->longitude
        ]);
        $data->distance = bcdiv($mapResult['result']['routes'][0]['distance'],1000,2);
        $data->status = 1;
        $data->save();
        $this->success($this->successMsg);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 回收订单--订单完成
     */
    public function overOrder()
    {
        $params = $this->request->post();
        if(empty($params))
            $this->error($this->warningMsg);
        extract($params);
        $model = new Order();
        $data = $model->find($order_id);
        if(empty($data))
            $this->error($this->warningMsg);
        if($data->status != 3)
            $this->error($this->errorMsg = '请耐心等候验车结束');
//        $service = new Aliocr();
//        if($face_image)
//        {
//            $result = $service->ocrIdcard(request()->domain().$face_image, 'face');
//            if ($result === false) {
//                $this->error('身份证识别失败');
//            }
//            $service_data = $service->data;
//            $data->username = $service_data['name'];
//            $data->genderdata = $service_data['sex'] == '男' ? 'male' : 'female';
//            $data->idcard = $service_data['num'];
//        }
        $data->face_image = $face_image;
        $data->back_image = $back_image;
        $data->enr_image = $enr_image;
        $data->letter_image = $letter_image;
        $data->contract_image = $contract_image;
        $data->yy_image = $yy_image;
        $data->status = 4;
        $data->overtime = time();
        $data->save();

        //给下单用户返余额
        \app\common\model\User::money($data->end_price,$data->userid,'回收订单'.$data->numbers.'收益到账');
        $this->success($this->successMsg);
    }

//    暂时不用，设计图不全
//    public function messageInfo()
//    {
//        if($this->request->isPost())
//        {
//            //提交留言
//            $params = $this->request->post();
//            if(empty($params))
//                $this->error($this->warningMsg);
//            $model = new Order();
//            $data = $model->find($params['order_id']);
//            if(empty($data))
//                $this->error($this->warningMsg);
//
//        }
//    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 检测预约前获取价格
     */
    public function getOrderPrice()
    {
        $params = $this->request->get();
        if(empty($params))
            $this->error($this->warningMsg);
        //查找用户所选检测厂
        $store = Lists::find($params['end_storeid']);
        if(empty($store))
            $this->error($this->warningMsg);
        $price = 0;
        $vehicle_info = Category::get(['name'=>$params['vehicle_type']]);
        if(empty($vehicle_info))
            $this->error($this->errorMsg = '暂不支持该类车辆检测');
        switch ($params['type']){
            case 1:
                //检测费
//                foreach ($store->json as $json)
//                {
//                    if($json['vehicle_type'] == $vehicle_info->id)
//                        $price = $json['vehicle_price'];
//                }
                $price = Prices::where(['vehicle_type'=>$vehicle_info->id,'type'=>$params['check_type']])->value('vehicle_price');
                if($price <= 0)
                    $this->error($this->errorMsg = '该检测厂不支持检测您的车辆');
                break;
            case 2:
                //代驾费,暂时写死，预估代驾费需要重改。需要传用户的位置信息，从而计算区到区的代驾费用
                $key = (new \app\api\model\wddj\Config())->where('id',1)->value('tencent_map_web_service_key');
                $city_result = getAddress($params['latitude'], $params['longitude'],$key);
                $store_result = getAddress($store->latitude, $store->longitude,$key);
                if(!$city_result)
                    throw new Exception('位置信息获取失败');
                $cityObj = (new \app\api\model\wddj\user\operation\City())->where('city','like','%'.$city_result['city'].'%')->find();
                if (empty($cityObj)) {
                    $this->error($this->errorMsg = '城市没有开通代驾服务');
                }
                $params['city_id'] = $cityObj['id'];

                //判断城市下的费用规则是否包含用户所选车辆类别
                $startingPrice = StartingPrice::where(['city_id'=>$params['city_id'],'vehicle_type'=>$vehicle_info->pid])->where("FIND_IN_SET(:id,area_names)",['id'=>$store_result['province'].'/'.$store_result['city'].'/'.$store_result['district']])->find();
                if(empty($startingPrice))
                    $this->error($this->errorMsg = '城市没有开通代驾服务');
                $price = bcmul($startingPrice['price'],2,2);
                break;
        }
        $this->success($this->successMsg,$price);
    }
    /**
     * @return void
     * 车辆检测
     */
    public function postCheckInfo()
    {
        $params = $this->request->post();
        if(empty($params))
            $this->error($this->warningMsg);
        $params['userid'] = $this->auth->id;
        $order_check = db('check_order')->where(['userid'=>$params['userid'],'plate_num'=>$params['plate_num']])->whereTime('createtime','year')->find();
//        if(!empty($order_check) && $order_check['status'] != -1)
//            $this->error('您的爱车'.$params['plate_num'].'已预约检测');
        $params['numbers'] = date('YmdHis',time()).Random::numeric(4);
        //查找用户所选检测厂
        $store = Lists::find($params['end_storeid']);
        if(empty($store))
            $this->error($this->warningMsg);
        $params['end_adminid'] = $store->admin_id;
        $params['end_name'] = $store->name;
        $params['end_tags'] = $store->tags;
//        $vehicle_type = [];
        $vehicle_info = Category::get(['name'=>$params['vehicle_type']]);
        if(empty($vehicle_info))
            $this->error($this->errorMsg = '暂不支持该类车辆检测');
//        foreach ($store->json as $json)
//        {
////            $vehicle_type[] = $json['vehicle_type'];
//            if($json['vehicle_type'] == $vehicle_info->id)
//                $params['end_price'] = $json['vehicle_price'];
//        }
        $params['end_price'] = Prices::where(['vehicle_type'=>$vehicle_info->id,'type'=>$params['type']])->value('vehicle_price');
        if(!isset($params['end_price']) || $params['end_price'] <= 0)
            $this->error($this->errorMsg = '该检测厂不支持检测您的车辆');
        $params['end_json'] = implode(',',$store->toArray()['json_text']);
        //计算用户位置与检测厂位置之间的距离
        $mapResult = (new Map())->get_driver_routes([
            'from_lat'=>$params['latitude'],
            'from_lng'=>$params['longitude'],
            'to_lat'=>$store->latitude,
            'to_lng'=>$store->longitude
        ]);
        $params['distance'] = bcdiv($mapResult['result']['routes'][0]['distance'],1000,2);
        $params['createtime'] = time();
        Db::startTrans();
        try {
            db('check_order')->insert($params);
            $wechat_id = User::getWechatId($params['userid']);
            $estimated_amount = $params['end_price'];
            $after_update = [];
            //判断是否需要代驾
            if($params['is_diving'] == 1)
            {
                $key = (new \app\api\model\wddj\Config())->where('id',1)->value('tencent_map_web_service_key');
                $city_result = getAddress($params['latitude'], $params['longitude'],$key);
                $store_result = getAddress($store->latitude, $store->longitude,$key);
                if(!$city_result || !$store_result)
                    throw new Exception('位置信息获取失败');
                //下代驾订单
                $car_order = [
                    'type'=> 2,
                    'city'=>  $city_result['city'],
                    'to_city'=>($store_result['province'].'/'.$store_result['city'].'/'.$store_result['district']),
                    'city_type'=>$vehicle_info->pid,//城市代驾规则中的车辆类型
                    'to_address'=> $store->address,
                    'to_lat'=> $store->latitude,
                    'to_lng'=> $store->longitude,
                    'from_address'=> $params['city'].$params['address'],
                    'from_lat'=> $params['latitude'],
                    'from_lng'=> $params['longitude'],
                    'driver_number'=> 1,
                    'departure_time'=> date('Y-m-d H:i',$params['gettime']),
                    'is_check'=>1
                ];
                $order_result = \app\api\model\wddj\user\Order::autoCreate($car_order,$wechat_id);
                if(!is_array($order_result))
                    throw new Exception($order_result);
                $order_result['estimated_amount'] = bcmul($order_result['estimated_amount'],2,2);
                $estimated_amount += $order_result['estimated_amount'];
                $after_update['out_trade_no'] = $order_result['out_trade_no'];
                $after_update['estimated_amount'] = $order_result['estimated_amount'];
            }
            $after_update['all_money'] = $estimated_amount;
            db('check_order')->where(['numbers'=>$params['numbers']])->update($after_update);
            $openid = wddj_get_openid($wechat_id);
            $estimated_amount = 0.01;
            $conf = Wxapp::unify('下单', $params['numbers'], $estimated_amount, $openid, request()->domain() . '/api/wddj/user/order/checkNotify');
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success($this->successMsg,$conf);
    }
    public function  checkComment()
    {
        $params = $this->request->post();
        $order = Orders::find($params('order_id'));
        if(!empty($order))
            $this->error('订单不存在');
        if($order->status != 3)
            $this->error($this->errorMsg = '订单未完成');
        $order->star_nums = $params['star_nums'];
        $order->comment = $params['comment'];
        $order->status = 4;
        $order->save();
        $this->success($this->successMsg);
    }
    /**
     * @return void
     * 自动取消订单
     */
    public function channelOrder()
    {
        $model = new Orders();
        $result = $model->where(['status'=>0,'createtime'=>['<',strtotime('-15 minutes')]])->update(['status'=>-1]);
        if($result)
            $this->success($this->successMsg);
        $this->error($this->errorMsg);
    }

    /**
     * @return void
     * 自动上下线
     */
    public function autoDriverStatus()
    {
        $time = time();
        $date = Date('H:i',$time);
        //需上线
        $ids = CertifiedDrivingAgent::where([
            'start_time'=>['<=',$date],
            'end_time'=>['>',$date],
            'state'=>2
        ])->where(['rest_begin'=>['>',$time]])->whereOr(['rest_end'=>['<',$time]])->column('id');
        Driver::where(['certified_id'=>['in',$ids],'status'=>'normal'])->update(['order_status'=>1]);
        Driver::where(['certified_id'=>['not in',$ids],'status'=>'normal'])->update(['order_status'=>2]);
        $this->success($this->successMsg);
    }

    /**
     * @return void
     * 用户钱包
     */
    public function moneyInfo()
    {
        $data['money'] = db('user_money_log')->where(['user_id'=>$this->auth->id])->sum('money');
        $data['not_money'] = Order::where(['userid'=>$this->auth->id,'status'=>['neq',4]])->sum('end_price');
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * @throws \think\exception\DbException
     * 钱包明细
     */
    public function moneyList()
    {
        $type = request()->post('type',0);
        $data = [];
        if($type == 1)
        {
            //提现
            $model = new Withdrawal();
            $data = $model->where(['userid'=>$this->auth->id])->order('id desc')->paginate();
        }else{
            //收入
            $data = db('user_money_log')->where(['user_id'=>$this->auth->id,'money'=>['>',0],'memo'=>['neq','提现驳回返回钱包']])->order('id','desc')->paginate();
        }
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * get获取银行账户信息，post提交提现
     */
    public function walletOut()
    {
        if($this->request->isPost())
        {
            //发起提现
            $params = $this->request->post();
            if(!isset($params['amount']) || $params['amount'] <= 0)
                $this->error($this->warningMsg = '请正确填写提现金额');
            if($params['amount'] < 100)
                $this->error($this->warningMsg = '最低提现金额100元');
            if(!isset($params['bank_name']) || $params['bank_name'] == '' || !isset($params['bank_card_number']) || $params['bank_card_number'] == '')
                $this->error($this->warningMsg = '请输入银行账户信息');
            $params['userid'] = $this->auth->id;
            $params['createtime'] = time();
            $res = db('user_withdrawal')->insert($params);
            if(!$res)
                $this->error($this->errorMsg);
            //开始扣除余额

            \app\common\model\User::money(-$params['amount'],$params['userid'],'提现扣除');
            $this->success($this->successMsg);
        }
        //获取上次提现的银行卡信息
        $data = db('user_withdrawal')->where(['userid'=>$this->auth->id])->order('id','desc')->field('bank_name,bank_card_number')->find();
        $this->success($this->successMsg,$data);
    }
    /**
     * @return void
     * 最近检测厂ID获取--代驾送检用
     */
    public function getNearStore()
    {
        $params = $this->request->param();
        if(empty($params))
            $this->error($this->warningMsg);
        extract($params);
        $where = 'o.status = 1';
        if(isset($type) && $type)
        {
            if($type == 'check')
                $where .= ' and o.type != 3';
            else
                $where .= ' and o.type != 1';
        }
        $data = Db::query("SELECT truncate(st_distance (POINT($user_lng,$user_lat), POINT(o.longitude,o.latitude))*111195/1000 , 2) as rsdistance,o.* FROM cc_detection AS o  WHERE $where  ORDER BY rsdistance ASC , o.createtime ASC limit 0,1");
        if(empty($data))
            $this->error($this->warningMsg = '附近没有检测厂');
        $this->success($this->successMsg,$data[0]['id']);
    }
}
